package top.lishuoboy.spring.jdbc_template.config;

import cn.hutool.db.ds.pooled.DbConfig;
import cn.hutool.db.ds.pooled.PooledDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import top.lishuoboy.spring.jdbc_template.config.properties.DbProperties;

import javax.sql.DataSource;

@Slf4j
@Configuration
@Import(DbProperties.class)
// 启用事务管理，相当于  <tx:annotation-driven transaction-manager="transactionManager"/>。区别是 @EnableTransactionManagement是byType，<tx:annotation-driven/> 是byName。
@EnableTransactionManagement
public class ApplicationConfiguration {
    @Autowired
    private DbProperties dbProps;

    /** 24.整合 h2 数据库、hutool 连接池、JdbcTemplate */
    @Bean
    DataSource dataSource() {
        log.debug("dbProps=={}", dbProps);
        DbConfig dbConfig = new DbConfig(dbProps.getUrl(), dbProps.getUser(), dbProps.getPass());
        dbConfig.setMaxActive(dbProps.getMaxActive());
        PooledDataSource pooledDataSource = new PooledDataSource(dbConfig);
        return pooledDataSource;
    }

    /** 24.整合 h2 数据库、hutool 连接池、JdbcTemplate */
    @Bean
    JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }

    @Bean
    DataSourceTransactionManager dataSourceTransactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}